package dryven.request.controller.result;

import java.io.OutputStreamWriter;
import java.io.Writer;

import dryven.util.json.JsonEncoder;
import dryven.view.ViewEngine;
import dryven.model.di.DependencyService;
import dryven.request.controller.ControllerDescription;
import dryven.request.http.Request;
import dryven.request.http.Response;

public class JsonResult implements ActionResult, OriginatingControllerListener {

	private Object _data;
	private JsonEncoder _enc;
	private DependencyService _di;
	
	public JsonResult(Object data) {
		super();
		_data = data;
	}
	
	public void injectDependencies(JsonEncoder encoder, DependencyService di) {
		if(_enc==null) {
			_enc = encoder;
		}
		if(_di==null) {
			_di = di;
		}
	}

	@Override
	public ActionResult process(Request req, Response resp) {
		if(_data!=null) {
			_di.injectDependencies(req, _data);
		}
		
		resp.setHeader("Content-Type", "application/json");
		try {
			Writer out = new OutputStreamWriter(resp.getResponseStream(),"UTF-8");
			_enc.encodeRootValue(_data, req, out);
			out.flush();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return null;
	}


	@Override
	public void passOriginatingController(ControllerDescription cd) {
		if(_data==null) {
			return;
		}

		if(_data!=null && OriginatingControllerListener.class.isAssignableFrom(_data.getClass())) {
			((OriginatingControllerListener)_data).passOriginatingController(cd);
		}
	}
}
